﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using LuaInterface;

namespace Timer
{
    public class TimerUtils
    {
        public static Dictionary<string, System.Threading.Timer> dicTimer = new Dictionary<string, System.Threading.Timer>();
        public static void AddTimer(string id ,LuaFunction L_function , int times , int period , int delay = 0 )
        {
            TimerVO vo = new TimerVO
            {
                delay = delay,
                times = times,
                period = period,
                L_function = L_function,
                id = id,
            };
            System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback((obj) => {
                TimerVO _vo = obj as TimerVO;
                _vo.currTimes++;
                _vo.HandlerCallFunction();
            }), vo, delay, period);//创建定时器
            dicTimer[id] = timer;
        }

        public static void RemoveTimer(string id)
        {
            var vo = dicTimer[id];
            if ( vo!= null)
            {
                vo.Dispose();
            }
            dicTimer[id] = null;
        }
    }

    public class TimerVO
    {
        public LuaFunction L_function;
        public int delay;       //延迟
        public int times;       //次数
        public int period;       //间隔时间

        public int currTimes = 0;
        public string id;

        public void HandlerCallFunction()
        {
            if(currTimes > times && times != -1)
            {
                //if (L_function != null)
                //{
                //    L_function.Call(true);
                //}
                TimerUtils.RemoveTimer(this.id);
                return;
            }
            else
            {
                if (L_function != null)
                {
                    L_function.Call(false);
                }
            }
        }

    }
}
